package Offer2019;

import java.util.concurrent.*;

/**
 * 线程池
 */
public class MyThreadPoolDemo {

    //public static void main(String[] args) {
    //    //ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池5个处理线程
    //    //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1个处理线程
    //    ExecutorService threadPool = Executors.newCachedThreadPool();//
    //
    //    try {
    //        //模拟10个用户来办理业务，每个业务就是一个来自外部的请求线程
    //        for (int i = 1; i <= 10; i++) {
    //            threadPool.execute(() -> {
    //                System.out.println(Thread.currentThread().getName()+"\t 办理业务");
    //            });
    //        }
    //
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    } finally {
    //        threadPool.shutdown();
    //    }
    //}

    public static void main(String[] args) {

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                //java.util.concurrent.RejectedExecutionException
                // new ThreadPoolExecutor.AbortPolicy());
                //不会抛弃任务，也不会抛出异常，而是其返回给调用者处理。这里是main
                //new ThreadPoolExecutor.CallerRunsPolicy());
                //超出最大承载不执行 不抛出异常
                //new ThreadPoolExecutor.DiscardPolicy());
                ////超出最大承载尝试和第一个线程竞争。竞争失败不执行 不抛出异常
                new ThreadPoolExecutor.DiscardOldestPolicy());

            try {
                for (int i = 1; i <= 9; i++) {
                    threadPool.execute(() -> {
                        System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                threadPool.shutdown();
            }
    }
}
